import os
from dataclasses import Field

from langchain import hub
from langchain.agents import create_tool_calling_agent, AgentExecutor, Tool, tool, initialize_agent, create_react_agent, \
    AgentType
from langchain.agents.format_scratchpad import format_log_to_str, format_to_openai_function_messages
from langchain.agents.output_parsers import ReActSingleInputOutputParser, OpenAIFunctionsAgentOutputParser
from langchain.memory import ConversationBufferMemory
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.tools import MoveFileTool, YahooFinanceNewsTool
from langchain_community.utilities import SerpAPIWrapper
from langchain_community.vectorstores import Chroma
from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, PromptTemplate
from langchain_core.tools import render_text_description, BaseTool


from langchain_core.utils.function_calling import convert_to_openai_function, format_tool_to_openai_function
from langchain_experimental.agents import create_csv_agent
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.tools.retriever import create_retriever_tool
from langchain_core.pydantic_v1 import BaseModel, Field

os.environ["LANGCHAIN_VERBOSE"] = "true"
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_PROJECT"] = "langchain_agent[1.0.3]"
os.environ["LANGCHAIN_API_KEY"] = "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"
os.environ["GOOGLE_API_KEY"] = "AIzaSyBJoz7BvdFgWTBwzcu-0xWpJKfEJOR6vPM"
os.environ['SERPAPI_API_KEY'] = '47afe0f70fefbe12e10919ee52248ac01d28652b763975bc84347a774805f3b6'

llm = ChatGoogleGenerativeAI(model="models/gemini-1.5-pro-latest", temperature=0.7)

embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")





def search_simple():
    search = SerpAPIWrapper()
    @tool
    def test_search(query: str):
        """这是一个说笑话的工具"""
        return search.run(query)


    tools = [MoveFileTool(), test_search,YahooFinanceNewsTool()]
    prompt = ChatPromptTemplate.from_messages(
        [
            (
                "system",
                "You are very powerful assistant, but bad at calculating lengths of words.",
            ),
            ("user", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad"),
        ]
    )

    model_with_functions = llm.bind_tools(tools)
    result = model_with_functions.invoke([HumanMessage("给我")])
    #result = llm.invoke([HumanMessage("帮我检索印尼今天印尼天气")])
    print(result)


    #agent = create_tool_calling_agent(llm, tools, prompt)
    # agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    # #message = agent_executor.invoke({"input":"move file F:/tmp/langchain/1.txt to F:/tmp/langchain/temp/2.txt"})
    # message = agent_executor.invoke({"input": "帮我检索印尼今天印尼天气"})
    #
    # print(message)


def agent_search_history():

    search = SerpAPIWrapper()
    tools = [Tool(
        name="search",
        func=search.run,
        description="当您需要回答有关时事或世界现状的问题时非常有用",
    ),]
    prompt = ChatPromptTemplate.from_messages(
        [
            (
                "system",
                "You are a helpful assistant. Make sure to use the tavily_search_results_json tool for information.",
            ),
            ("placeholder", "{chat_history}"),
            ("human", "{input}"),
            ("placeholder", "{agent_scratchpad}"),
        ]
    )
    agent = create_tool_calling_agent(llm, tools, prompt)
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

    result = agent_executor.invoke(
        {
            "input": "刘德华在2025年有什么电影将会在中国上映?用json格式输出",
            "chat_history": [
                HumanMessage(content="hi! my name is bob"),
                AIMessage(content="Hello Bob! How can I assist you today?"),
            ],
        }
    )
    print(result)


def tool_simple():
    class SearchInput(BaseModel):
        query: str = Field(description="should be a search query")
        demo : str  = Field(description="should be a search query")

    @tool("search-tool", args_schema=SearchInput, return_direct=True)
    def search(query: str) -> str:
        """Look up things online."""
        return "LangChain"

    print(search.name)
    print(search.description)
    print(search.args)
    print(search.return_direct)


def agent_csv_demo():
    agent = create_csv_agent(
        llm,
        "",
        verbose=True,
        agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    )
    result = agent.invoke({"input": "how many rows are there?"})
    print(result)





if __name__ == '__main__':
    agent_search_history()
